<?php
/**
 * Created by PhpStorm.
 * User: kkw
 * Date: 2019/1/28
 * Time: 16:26
 */
/**
 *      添加分类
 *
 *
 */
namespace kkw\admin\response;
use kkw\user\Util;
use kkw\admin\table\GoodsTypeTable;
use suda\core\Request;
use suda\core\Response;

class GoodsTypeResponse extends  Response
{

    public function onRequest(Request $request)
    {
        // 设置请求头
        Util::printHeader();
        // 实例化数据表
        $goods_type = new GoodsTypeTable();
        // 接收前台数据
        //$json = Request::json();
        // 接收前台数据
        $name = Request::post('name');
        $describe = Request::post('describe');

        // 插入数据
        // 上传图片开始
        $file = Request::files('file');
        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $saveName = substr(md5($file['tmp_name']), 0, 10) . '.' . $ext;
        $path = APP_PUBLIC . '/upload/';
        if (!is_dir($path)) {
            mkdir($path);
        }
        move_uploaded_file($file['tmp_name'], $path . '/' . $saveName);
        // 上传图片结束

        try {
            $goods_type->insert([
                'name'=>  $name,
                'describe'=> $describe,
                'img'=>$saveName,
            ]);
        } catch (\suda\exception\SQLException $e) {
            $this->json(['code' => $e->getCode(), 'message' => '添加商品分类失败']);
            return;
        }
        $this->json(['code' => 0, 'message' => '添加商品分类成功']);
    }
}